<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="培训" data-page-identification="r_r40a0k0zas">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_hludvvyuwr 自定义模板_e9v1m4bggb -->
            <a-modal title="预览" :footer="null" v-model:visible="previewState.previewVisible" @cancel="handleCancel"
                width="80vw" :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }" centered>
                <div class="middle-div" v-if="previewState.isImagePreview">
                    <img class="middle-div" :src="previewState.previewImage" alt="附件" style="width: 100%" />
                </div>
                <div class="middle-div" v-if="previewState.isDocPreview">
                    <vue-office-docx class="middle-div" :src="previewState.previewFileUrl" @rendered="renderedHandler"
                        @error="errorHandler" />
                </div>
                <div v-if="previewState.isPdfPreview">
                    <vue-office-pdf class="middle-div" :src="previewState.previewFileUrl" @rendered="renderedHandler"
                        @error="errorHandler" />
                    <iframe v-if="false" :src="previewState.previewFileUrl" style="width: 100%; height: 800px"></iframe>
                </div>
                <div v-if="previewState.isExcelPreview">
                    <vue-office-excel class="middle-div" :src="previewState.previewFileUrl" :options="options"
                        @rendered="renderedHandler" @error="errorHandler" />
                </div>
                <div v-show="previewState.isViedoPreview">
                    <video class="middle-div" autoplay :src="previewState.previewFileUrl" id="video-player" controls
                        controlslist="nodownload"></video>
                </div>
            </a-modal>
            <!--          预览附件-->
            <!--          平台新建/编辑培训-->
            <a-modal :visible="pxState.handleTrainVisible" :title="pxState.platformTitle" width="800px"
                @ok="handleConfirmTrain" @cancel="trainCancel" :ok-button-props="{ loading: trainLoading }" maskClosable
                centered :body-style="{
                    paddingBottom: 0
                }">
                <a-spin :spinning="trainLoading" tip="附件上传中，请稍后...">
                    <a-form ref="platTrainRef" :model="pxState.trainForm">
                        <div class="px-form">
                            <a-row v-if="activeKey === '平台产品'">
                                <a-col :span="12">
                                    <a-form-item label="项目名称"
                                        :rules="[{ required: true, message: '请选择项目名称', trigger: 'blur' }]"
                                        name="projectName">
                                        <a-select show-search allow-clear @focus="getProjectList"
                                            v-model:value="pxState.trainForm.projectName"
                                            :options="pxState.projectNameList" @change="projectNameChange"
                                            :field-names="{ label: 'label', value: 'label' }" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item label="版本号" :rules="[
                                        { required: true, message: '请输入数字', trigger: 'blur' },
                                        {
                                            pattern: /^[0-9]+(\.[0-9]{1,2})?$/,
                                            message: '请输入最多小数点后两位的正数数字',
                                            trigger: 'blur'
                                        }
                                    ]" name="version">
                                        <a-input-number v-model:value="pxState.trainForm.version" />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item label="课程说明">
                                        <a-textarea v-model:value="pxState.trainForm.description" />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-form-item label="上传附件"
                                    :rules="[{ required: true, message: '请上传附件', trigger: 'blur' }]" name="fileList">
                                    <a-upload v-model:file-list="pxState.trainForm.fileList" :multiple="true"
                                        :before-upload="handlerTrainUpload" @remove="handlerTrainRemove"
                                        accept=".xlsx, image/*,.docx,, .xls,.mp4">
                                        <a-button type="primary">
                                            <upload-outlined />
                                            上传
                                        </a-button>
                                    </a-upload>
                                    <span>支持格式：.xlsx, image/*,.docx,, .xls,.mp4</span>
                                    <div class="tip">上传前对文件进行解密</div>
                                </a-form-item>
                            </a-row>
                        </div>
                    </a-form>
                </a-spin>
            </a-modal>
            <!--          平台新建/编辑培训-->
            <div class="search-div" v-if="activeKey !== '平台产品'">
                <a-form :model="pxState.searchForm" ref="ptSearchRef">
                    <a-row :gutter="24" style="height: 32px">
                        <a-col :span="4" style="height: 32px; margin-top: 20px">
                            <a-form-item label="项目阶段">
                                <a-select show-search placeholder="请选择" @focus="getMilepostList"
                                    v-model:value="pxState.searchForm.milepostId" :options="pxState.miltpostList"
                                    :field-names="{ label: 'milepostName', value: 'templateStageId' }"
                                    @change="milepostChange" />
                            </a-form-item>
                        </a-col>

                        <a-col :span="4" style="height: 32px; margin-top: 20px">
                            <a-form-item label="任务名称">
                                <a-select show-search :filter-option="(input, option) => {
                                        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    " allow-clear @focus="getTaskList" v-model:value="pxState.searchForm.taskId"
                                    :options="pxState.taskList" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="3" style="height: 32px; margin-top: 20px"><a-space><a-button type="primary"
                                    @click="getTemplateData">查询</a-button> <a-button type="default"
                                    @click="resetTemplateData">重置</a-button></a-space></a-col>
                    </a-row>
                </a-form>
            </div>
            <div class="search-div" v-else>
                <a-form :model="pxState.searchForm" ref="searchRef">
                    <a-row :gutter="24" style="height: 32px">
                        <a-col :span="4" style="height: 32px; margin-top: 20px">
                            <a-form-item label="项目名称">
                                <a-select show-search allow-clear @focus="getProjectList"
                                    v-model:value="pxState.searchForm.projectName" :options="pxState.projectNameList"
                                    @change="projectNameChange" :field-names="{ label: 'label', value: 'label' }" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="4" style="height: 32px; margin-top: 20px">
                            <a-form-item label="版本号">
                                <a-select show-search allow-clear @focus="getVersiontList"
                                    :field-names="{ label: 'label', value: 'label' }"
                                    v-model:value="pxState.searchForm.version" :options="pxState.versionList" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="3" style="height: 32px; margin-top: 20px"><a-space><a-button type="primary"
                                    @click="getPlatformData">查询</a-button> <a-button type="default"
                                    @click="resetPlatformData">重置</a-button></a-space></a-col>
                    </a-row>
                </a-form>
            </div>
            <div class="kb-page">
                <a-tabs v-model:activeKey="activeKey" size="large" :tabBarGutter="24" @change="tabChange(activeKey)">
                    <a-tab-pane key="55家新水泥配料" tab="55家新水泥配料" />
                    <a-tab-pane key="水泥配料" tab="水泥配料" />
                    <a-tab-pane key="平台产品" tab="平台产品" />
                </a-tabs>
                <div class="table-body" v-if="activeKey !== '平台产品'">
                    <div class="template-title">
                        <div v-if="radioValue === '1'"><span class="title-font">任务列表</span></div>
                        <div v-else><span class="title-font">项目阶段列表</span></div>
                        <div>
                            <a-radio-group v-model:value="radioValue" button-style="solid" @change="radioChange">
                                <a-radio-button value="2">项目阶段</a-radio-button>
                                <a-radio-button value="1">任务</a-radio-button>
                            </a-radio-group>
                        </div>
                    </div>
                    <div class="default-table">
                        <a-table bordered :columns="templateColumns" :data-source="pxState.templateData"
                            @resizeColumn="handleTaskResizeColumn">
                            <template #bodyCell="{ text, column, record }">
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-button type="link" size="small" @click="handleEditTrain(record)">编辑</a-button>
                                    <a-popconfirm :disabled="!record.id" title="确定要删除吗？"
                                        @confirm="handleDeleteTrain(record)">
                                        <a-button :disabled="!record.id" size="small" type="link">删除</a-button>
                                    </a-popconfirm>
                                </template>
                                <template v-if="column.dataIndex === 'file'">
                                    <div class="file-div" v-for="(item, index) in record.fileList"
                                        @click="previewAttachment(item)"> {{ item.name }}</div>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
                <div class="table-body" v-else>
                    <div class="template-title">
                        <div><span class="title-font">培训视频列表</span></div>
                        <div><a-button @click="handleAddTrain" type="primary">
                                <template #icon>
                                    <PlusOutlined />
                                </template> 新建</a-button></div>
                    </div>
                    <div class="default-table">
                        <a-table bordered :columns="columns" :data-source="pxState.platformData"
                            @resizeColumn="handleTaskResizeColumn">
                            <template #bodyCell="{ column, record, text }">
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-button type="link" size="small" @click="handleEditTrain(record)">编辑</a-button>

                                    <a-popconfirm title="确定要删除吗？" @confirm="handleDeleteTrain(record)">
                                        <a-button size="small" type="link">删除</a-button>
                                    </a-popconfirm>
                                </template>
                                <template v-if="column.dataIndex === 'file'">
                                    <div class="file-div" v-for="(item, index) in record.fileList"
                                        @click="previewAttachment(item)"> {{ item.name }}</div>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>
            <!-- end vid_hludvvyuwr 自定义模板_e9v1m4bggb -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
import {
    h, ref, reactive, toRaw, markRaw, watch, computed,
    onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
} from "vue";
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();
import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
import dayjs from 'dayjs';
import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
import { message, notification, Modal } from 'ant-design-vue'
import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
import colorTheme from '@/design/custom-theme.json';
/*** PUBLISH_EXEGESIS ***
import UserTableRecords from '@/model/UserTableRecords';
import { getAppBaseUrl } from '@/utils/index';
import { sendToken } from "@/hooks/useIframeToken";
import { useSystemStore } from "@/store/modules/system";
const systemStore = useSystemStore();
*** PUBLISH_EXEGESIS ***/



// 获取传入的流程ID和组件参数
const props = defineProps({
    'processInstanceId': {
        type: [String, Number, Boolean],
        default: undefined,
    },
})
const immediateWatch = (source, callback) => {
    watch(source, callback, { deep: true, immediate: true })
}



/* -------------------------- 属性定义 -------------------------- */

const setTimeOutList = [];
const pageLoading = reactive({
    loading: false,
    tip: undefined
});
const authInfo = localGet('app-user-store');




// 处理校验
const setSubFormName = (parentInfo, name) => {
    return [parentInfo.parents, parentInfo.cycleIndex, name];
}


/* ========================== 属性定义 ========================== */


/* -------------------------- 元素数据引用 -------------------------- */


/* ========================== 元素数据引用 ========================== */


/* -------------------------- 页面数据 -------------------------- */


/* ========================== 页面数据 ========================== */



/* -------------------------- 响应 -------------------------- */

/* ========================== 响应 ========================== */


/* -------------------------- 函数 -------------------------- */

/* ========================== 函数 ========================== */


/* -------------------------- 页面参数 -------------------------- */

const pageParameter_state = reactive({
    'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
})

/* ========================== 页面参数 ========================== */


/* -------------------------- 组件事件处理方法 -------------------------- */

// ---------------------------- 组件数据同步 ----------------------------

// ============================ 组件数据同步 ============================


/* ========================== 组件事件处理方法 ========================== */


/* -------------------------- 生命周期 -------------------------- */
// 用于参数变更后重新执行自定义指令
const queryUpdateFlag = ref(0);
onMounted(() => {
    ;

});

onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ? clearInterval(timer) : clearTimeout(timer);
    });
});

/* ========================== 生命周期 ========================== */


/* -------------------------- 数据关联处理 -------------------------- */





/* -------------------------- 表单数据同步 -------------------------- */
/* ========================== 表单数据同步 ========================== */

/* ========================== 数据关联处理 ========================== */


/* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

/* ========================== 不同组件自定义的处理逻辑 ========================== */


// ================================定制化逻辑========================================
import { nextTick } from 'vue'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficeDocx from '@vue-office/docx'
const previewState = reactive({
    previewVisible: false,
    previewImage: '',
    previewFileUrl: '',
    isImagePreview: false,
    isDocPreview: false,
    isPdfPreview: false,
    isExcelPreview: false,
    isViedoPreview: false
})

function previewAttachment(item) {
    if (item.type.startsWith('image')) {
        previewState.isExcelPreview = false
        previewState.isImagePreview = true
        previewState.isDocPreview = false
        previewState.isViedoPreview = false
        previewState.isPdfPreview = false
        previewState.previewImage = item.url // 设置预览图片的URL
        previewState.previewVisible = true // 显示模态框
    }
    // else if (isDocFile(item.name, '.pdf')) {
    //     nextTick(() => {
    //         previewState.previewVisible = true // 显示模态框
    //         previewState.previewFileUrl = item.url // 设置预览PDF的URL
    //         previewState.isImagePreview = false
    //         previewState.isDocPreview = false
    //         previewState.isViedoPreview = false
    //         previewState.isExcelPreview = false
    //         previewState.isPdfPreview = true
    //     })
    // }
    else if (isDocFile(item.name, '.doc')) {
        previewState.isImagePreview = false
        previewState.isDocPreview = true
        previewState.isViedoPreview = false
        previewState.isPdfPreview = false
        previewState.isExcelPreview = false
        previewState.previewFileUrl = item.url // 设置预览WORD的URL
        previewState.previewVisible = true // 显示模态框
    } else if (isDocFile(item.name, '.docx')) {
        previewState.isExcelPreview = false
        previewState.isImagePreview = false
        previewState.isViedoPreview = false
        previewState.isDocPreview = true
        previewState.isPdfPreview = false
        previewState.previewFileUrl = item.url // 设置预览WORD的URL
        previewState.previewVisible = true // 显示模态框
    } else if (isDocFile(item.name, '.xls')) {
        options.value.xls = true
        previewState.isViedoPreview = false
        previewState.isImagePreview = false
        previewState.isDocPreview = false
        previewState.isPdfPreview = false
        previewState.isExcelPreview = true
        previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
        previewState.previewVisible = true // 显示模态框
    } else if (isDocFile(item.name, '.xlsx')) {
        options.value.xls = false
        previewState.isImagePreview = false
        previewState.isDocPreview = false
        previewState.isPdfPreview = false
        previewState.isViedoPreview = false
        previewState.isExcelPreview = true
        previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
        previewState.previewVisible = true // 显示模态框
    } else if (item.type.startsWith('video')) {
        options.value.xls = false
        previewState.isImagePreview = false
        previewState.isDocPreview = false
        previewState.isPdfPreview = false
        previewState.isViedoPreview = true
        previewState.isExcelPreview = false
        previewState.previewFileUrl = item.url // 设置预览EXCEL的URL
        previewState.previewVisible = true // 显示模态框
        nextTick(() => {
            let video = document.querySelector('#video-player')
            console.log(video)
            video?.requestFullscreen()
        })
    } else {
        message.warning('暂不支持的文件格式')
    }
}

function isDocFile(fileName, str) {
    return fileName.toLowerCase().endsWith(str)
}

function handleCancel() {
    previewState.isExcelPreview = false
    previewState.isImagePreview = false
    previewState.isDocPreview = false
    previewState.isViedoPreview = false
    previewState.isPdfPreview = false
    previewState.previewVisible = false // 显示模态框
}

function renderedHandler() {
    message.success('渲染成功')
}

function errorHandler(e) {
    message.error('渲染失败')
    console.log(e)
}

const options = ref({
    xls: true, //预览xlsx文件设为false；预览xls文件设为true
    minColLength: 0, // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
    minRowLength: 0, // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
    widthOffset: 10, //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
    heightOffset: 10 //在默认渲染的列表高度上再加 Npx高
})
onMounted(() => {
    if (activeKey.value !== '平台产品') {
        getTemplateData()
    } else {
        getPlatformData()
    }
    get('/solution-ppm/api/v2/built-in-system-ppm/train/permission').then(data => {
        pxState.auth = data.data
    })
})
const activeKey = ref('55家新水泥配料')
const radioValue = ref('1')
const pxState = reactive({
    auth: false,
    searchForm: {
        templateName: activeKey.value,
        projectName: undefined,
        version: undefined,
        pageNo: 1,
        pageSize: 999999,
        milepostName: undefined,
        taskName: undefined,
        taskId: undefined,
        milepostId: undefined
    },
    taskList: [],
    regionList: [],
    miltpostList: [],
    projectNameList: [],
    versionList: [],
    //   平台表格数据
    platformData: [],
    // 模板表格数据
    templateData: [],
    //   模板新建表单
    handleTrainVisible: false,
    platformTitle: '',
    trainForm: {
        projectName: undefined,
        version: undefined,
        description: undefined,
        fileList: [],
        type: undefined,
        templateTaskId: undefined,
        templateStageId: undefined,
        templateTaskId: undefined
    }
})
const trainLoading = ref(false)
const columns = ref([
    {
        title: '项目名称',
        dataIndex: 'projectName',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '版本号',
        dataIndex: 'version',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '课程说明',
        dataIndex: 'description',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '课程文件',
        dataIndex: 'file',
        align: 'center',
        resizable: true,
        width: 300
    },
    {
        title: '最新操作人',
        dataIndex: 'updateBy',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 130
    },
    {
        title: '最新提交时间',
        dataIndex: 'updateTime',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 150
    },
    {
        title: '操作',
        dataIndex: 'opration',
        align: 'center',
        width: 130
    }
])
const templateColumns = ref([
    {
        title: '项目阶段',
        dataIndex: 'milepostName',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '任务名称',
        dataIndex: 'taskName',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '课程说明',
        dataIndex: 'description',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 280
    },
    {
        title: '课程文件',
        dataIndex: 'file',
        align: 'center',
        resizable: true,
        width: 300
    },
    {
        title: '最新操作人',
        dataIndex: 'updateBy',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 130
    },
    {
        title: '最新提交时间',
        dataIndex: 'updateTime',
        align: 'center',
        ellipsis: true,
        resizable: true,
        width: 150
    },
    {
        title: '操作',
        dataIndex: 'opration',
        align: 'center',
        width: 130
    }
])
const templateCleep = cloneDeep(templateColumns.value)

function tabChange(key) {
    activeKey.value = key
    pxState.searchForm.templateName = key
    if (activeKey.value !== '平台产品') {
        getTemplateData()
    } else {
        getPlatformData()
    }
}

// 模板项目查项目阶段
function getMilepostList() {
    post('/solution-ppm/api/v2/built-in-system-ppm/train/template_stage/search', pxState.searchForm).then(data => {
        processingData(data, 'miltpostList', null)
    })
}

// 模板项目查任务
function getTaskList() {
    post('/solution-ppm/api/v2/built-in-system-ppm/train/template_task/', {
        milepostId: pxState.searchForm.milepostId
    }).then(data => {
        processingData(data, 'taskList', null)
    })
}

// 模板项目项目阶段变化清空任务框
function milepostChange(value) {
    if (!value) {
        pxState.searchForm.taskId = undefined
    }
}

// 平台项目项目名称变化清空版本
function projectNameChange(value) {
    if (!value) {
        pxState.searchForm.version = undefined
    }
}

// 获取平台产品培训列表
function getPlatformData() {
    post('/solution-ppm/api/v2/built-in-system-ppm/train/platform/search', pxState.searchForm).then(data => {
        processingData(data, 'platformData', null)
    })
}

// 重置平台产品培训列表
function resetPlatformData() {
    resetData(pxState.searchForm)
    getPlatformData()
}

// 获取模板产品培训列表
function getTemplateData() {
    if (radioValue.value === '1') {
        post('/solution-ppm/api/v2/built-in-system-ppm/train/template_task/search', pxState.searchForm).then(
            data => {
                processingData(data, 'templateData', null)
            }
        )
    } else {
        post('/solution-ppm/api/v2/built-in-system-ppm/train/template_stage/search', pxState.searchForm).then(
            data => {
                processingData(data, 'templateData', null)
            }
        )
    }
}

function radioChange() {
    if (radioValue.value === '1') {
        post('/solution-ppm/api/v2/built-in-system-ppm/train/template_task/search', pxState.searchForm).then(
            data => {
                processingData(data, 'templateData', null)
            }
        )
        templateColumns.value = templateCleep
    } else {
        post('/solution-ppm/api/v2/built-in-system-ppm/train/template_stage/search', pxState.searchForm).then(
            data => {
                processingData(data, 'templateData', null)
            }
        )
        templateColumns.value = templateColumns.value.filter(item => item.title !== '任务名称')
    }
}

// 重置模板产品培训列表
function resetTemplateData() {
    resetData(pxState.searchForm)

    getTemplateData()
}

//     获取平台项目项目名称
function getProjectList() {
    post('/solution-ppm/api/v2/built-in-system-ppm/train/platform_project', {}).then(data => {
        processingData(data, 'projectNameList', null)
    })
}

//     获取平台项目版本号
function getVersiontList() {
    post('/solution-ppm/api/v2/built-in-system-ppm/train/version', {
        projectName: pxState.searchForm.projectName
    }).then(data => {
        processingData(data, 'versionList', null)
    })
}

// 处理数据及异常
function processingData(data, target, msg) {
    if (data.code === 200) {
        if (!target) {
            message.success(msg)
        } else {
            if (data.data.dataList !== undefined) {
                pxState[target] = data.data.dataList
            } else {
                pxState[target] = data.data
            }
        }
        return true
    } else {
        message.error(data.message)
        return false
    }
}

//     新建课程
function handleAddTrain() {
    if (!pxState.auth) {
        message.info('暂无权限')
        return
    }
    pxState.handleTrainVisible = true
    pxState.trainForm.type = 0
    pxState.platformTitle = '新建课程内容'
}

//     新建课程
function handleTaskResizeColumn(w, col) {
    col.width = w
}

//     编辑课程
function handleEditTrain(record) {
    if (!pxState.auth) {
        message.info('暂无权限')
        return
    }
    let newData = cloneDeep(record)

    // 遍历pxState.trainForm的键并赋值
    for (let key in pxState.trainForm) {
        if (newData.hasOwnProperty(key)) {
            pxState.trainForm[key] = newData[key]
        }
    }
    pxState.trainForm.id = newData.id
    if (activeKey.value !== '平台产品') {
        pxState.trainForm.type = radioValue.value
    }
    pxState.handleTrainVisible = true
    pxState.platformTitle = '编辑课程内容'
}

//     编辑课程

// 删除课程
function handleDeleteTrain(record) {
    if (!pxState.auth) {
        message.info('暂无权限')
        return
    }
    del(`/solution-ppm/api/v2/built-in-system-ppm/train/${record.id}`).then(data => {
        if (processingData(data, false, '删除成功')) {
            getPlatformData()
            getTemplateData()
        }
    })
}

// 删除课程

//     平台新建/编辑保存
const platTrainRef = ref(null)

function handleConfirmTrain() {
    if (activeKey.value !== '平台产品') {
        if (!pxState.trainForm.id) {
            // 新建
            platTrainRef.value.validate().then(() => {
                post('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm).then(data => {
                    if (processingData(data, false, '新建成功')) {
                        getTemplateData()
                        pxState.handleTrainVisible = false
                        resetData(pxState.trainForm)
                    }
                })
            })
        } else {
            //   编辑保存
            platTrainRef.value.validate().then(() => {
                put('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm).then(data => {
                    if (processingData(data, false, '编辑成功')) {
                        getTemplateData()
                        pxState.handleTrainVisible = false
                        resetData(pxState.trainForm)
                    }
                })
            })
        }
    } else {
        if (!pxState.trainForm.id) {
            // 新建
            platTrainRef.value.validate().then(() => {
                post('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm).then(data => {
                    if (processingData(data, false, '新建成功')) {
                        getPlatformData()
                        pxState.handleTrainVisible = false
                        resetData(pxState.trainForm)
                    }
                })
            })
        } else {
            //   编辑保存
            platTrainRef.value.validate().then(() => {
                put('/solution-ppm/api/v2/built-in-system-ppm/train', pxState.trainForm).then(data => {
                    if (processingData(data, false, '编辑成功')) {
                        getPlatformData()
                        pxState.handleTrainVisible = false
                        resetData(pxState.trainForm)
                    }
                })
            })
        }
    }
}

function trainCancel() {
    pxState.handleTrainVisible = false
    resetData(pxState.trainForm)
}

function resetData(data) {
    for (let key in data) {
        if (data.hasOwnProperty(key)) {
            if (Array.isArray(data[key])) {
                data[key] = []
            } else if (typeof data[key] === 'object' && data[key] !== null) {
                data[key] = {}
            } else {
                if (key === 'pageSize') {
                    data[key] = 999999
                } else if (key === 'pageNo') {
                    data[key] = 1
                } else if (key === 'templateName') {
                    data[key] = activeKey.value
                } else {
                    data[key] = undefined
                }
            }
        }
    }
    return data // 返回重置后的数据
}

const count = ref([])
const successCount = ref(0)

// 上传文件
function handlerTrainUpload(file) {
    count.value.push(file)
    if (
        !(
            file.type.startsWith('image') ||
            // isDocFile(file.name, '.pdf') ||
            isDocFile(file.name, '.docx') ||
            isDocFile(file.name, '.xls') ||
            isDocFile(file.name, '.xlsx') ||
            file.type.startsWith('video')
        )
    ) {
        message.info('有不支持的文件格式')
        return
    }
    trainLoading.value = true
    const data = new FormData()
    data.append('file', file)

    post('/file-storage/api/v1/file/upload', data)
        .then(({ data: { fullUrl } }) => {
            successCount.value++
            if (data) {
                // 新文件对象
                const newFile = {
                    uid: file.uid,
                    lastModified: file.lastModified,
                    name: file.name,
                    size: file.size,
                    type: file.type,
                    status: 'done',
                    url: fullUrl
                }

                // 去重，保留一个副本
                pxState.trainForm.fileList = [
                    // 保留已存在文件（去除重复）
                    ...pxState.trainForm.fileList.filter(item => item.uid !== file.uid && item.name !== file.name),
                    // 添加新的文件
                    newFile
                ]
            }
        })
        .catch(e => {
            message.error('上传失败' + e)
        })
        .finally(() => {
            if (successCount.value == count.value.length) {
                trainLoading.value = false
                successCount.value = 0
                count.value = []
            }
        })

    return false
}

// 移除文件
function handlerTrainRemove(file) {
    pxState.trainForm.fileList = pxState.trainForm.fileList.filter(item => item.uid !== file.uid)
}
</script>
<style lang="less" scoped>
.page_root {
    width: 100%;
    height: 100%;
    overflow: auto;
}

.page_root :deep(.@{ant-prefix}-spin-nested-loading),
.page_root :deep(.@{ant-prefix}-spin-container) {
    height: 100%;
}

.page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
    display: flex;
    flex-flow: column nowrap;
    justify-content: flex-start;
}

.page_root :deep(.@{ant-prefix}-table) {
    flex: auto;
    overflow: auto;
}

.table-moreBtn_down {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100px;
}

.table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
}

/*  表格树结构样式处理，展开按钮层级增加*/
:deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
}

/*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
:deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
}

:deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
}

:deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
}

:deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
}

/* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
:deep(.@{ant-prefix}-transfer-list) {
    height: 100%;
    width: 50%;
}


.search-div {
    background-color: #fff;
    margin-bottom: 16px;
    height: 72px;
    padding: 0 20px;
    border-radius: 6px;
}

.default-table:deep(.@{ant-prefix}-table-thead)>tr>th {
    background-color: #3875ff;
    color: #fff;
    font-weight: 600;
    padding: 8px 16px;
    border-right: 1px solid #d9d9d9;
}

.default-table:deep(.@{ant-prefix}-table-tbody) tr>td {
    font-size: 14px;
    font-family: arial, helvetica, 'microsoft yahei';
    font-weight: 400;
    color: #262626;
    padding: 8px 8px;
    border-bottom: 1px solid #d9d9d9;
    word-break: break-all;
}

.kb-page {
    padding: 0 20px 20px 20px;
    height: 100%;
    position: relative;
    background-color: #fff;
    border-radius: 6px;
}

.template-title {
    margin-top: 10px;
    padding-left: 8px;
    font-size: 16px;
    height: 24px;
    line-height: 24px;
    font-weight: 800px;
    border-left: 4px solid #3875ff;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.title-font {
    font-weight: 800;
}

:deep(.ant3-input-number) {
    width: 100%;
}

:deep(.px-form .ant3-form-item-label) {
    width: 80px !important;
}

.file-div {
    color: #3875ff;
    cursor: pointer;
}

.tip {
    font-weight: 800;
}

.middle-div {
    margin: 0 auto;
}
</style>